<template>
    <div class="dialogue">
        <header id="wx-header">
            <div class="other">
                <router-link :to="{path:'/wechat/dialogue/dialogue-info',query: { msgInfo: msgInfo}}" tag="span"
                    class="iconfont icon-chat-group" v-show="$route.query.group_num&&$route.query.group_num!=1">
                </router-link>
                <router-link :to="{path:'/wechat/dialogue/dialogue-detail',query: { msgInfo: msgInfo}}" tag="span"
                    class="iconfont icon-chat-friends" v-show="$route.query.group_num==1"></router-link>
            </div>
            <div class="center">
                <router-link to="/" tag="div" class="iconfont icon-return-arrow">
                    <span>大V看盘</span>
                </router-link>
                <span @click="scrollToBottomSpan">{{pageName}}</span>
            </div>
        </header>
      <div class="modal" v-if="showModal" @click.self="closeModal()">
        <img :src="currentImageUrl" class="modal-content">
      </div>
        <section class="dialogue-section clearfix" v-on:click="MenuOutsideClick" ref="dialogueSection">
              <div class="row" v-for="(item,index) in msgInfo.msg.slice(-400)" :key="index">
              <span class="msg_time" v-if="shouldShowTimestamp(index)">{{ formatTimestamp(item.date)}}</span>
                <div class="msg_item">
                  <img :src="msgInfo.msg[0].headerUrl" class="header">
                    <p class="text" v-more v-html="parseText(item.text)"></p>
                </div>
            </div>
        </section>
    </div>
</template>
<script>
    // import marked from 'marked';

    export default {
        data() {
            return {
                pageName: this.$route.query.name,
                currentChatWay: true, //ture为键盘打字 false为语音输入
                timer: null,
              savedScrollPosition: 0,
              showModal: false, // 控制模态框的显示
              currentImageUrl: '' // 存储当前点击的图片URL
                // sayActive: false // false 键盘打字 true 语音输入
            }
        },
      beforeRouteLeave(to, from, next) {
        // 保存当前的滚动位置
        const scrollPosition = sessionStorage.getItem('savedScrollPosition');
        console.log(scrollPosition)
        if (scrollPosition) {
          window.scrollTo(0, scrollPosition);
        }
        next();
      },
      beforeRouteEnter(to, from, next) {
            next(vm => {
              const scrollPosition = window.scrollY;
              console.log(window.scrollY)
              sessionStorage.setItem('savedScrollPosition', scrollPosition);
                vm.$store.commit("setPageName", vm.$route.query.name)
            })
        },

      mounted() {
        // this.scrollToBottom();
          setTimeout(() => {
            window.scrollTo(0, 99999999);
          }, 1000);
      },
        computed: {
            msgInfo() {
                for (var i in this.$store.state.msgList.baseMsg) {
                    if (this.$store.state.msgList.baseMsg[i].mid == this.$route.query.mid) {
                        return this.$store.state.msgList.baseMsg[i]
                      // return this.$store.state.msgList.baseMsg[i].slice(0, 50);
                    }
                }
                return {}
            }
        },
        directives: {
            press: {
                inserted(element) {
                    var recording = document.querySelector('.recording'),
                        recordingVoice = document.querySelector('.recording-voice'),
                        recordingCancel = document.querySelector('.recording-cancel'),
                        // startTx,
                        startTy

                    element.addEventListener('touchstart', function (e) {
                        // 用bind时，vue还没插入到dom,故dom获取为 undefine，用 inserted 代替 bind,也可以开个0秒的定时器
                        element.className = "chat-say say-active"
                        recording.style.display = recordingVoice.style.display = "block"
                        var touches = e.touches[0]
                        // startTx = touches.clientX
                        startTy = touches.clientY
                        e.preventDefault()
                    }, false)
                    element.addEventListener('touchend', function (e) {
                        element.className = "chat-say"
                        recordingCancel.style.display = recording.style.display = recordingVoice.style.display = "none"
                        e.preventDefault()
                    }, false)
                    element.addEventListener('touchmove', function (e) {
                        var touches = e.changedTouches[0],
                            // endTx = touches.clientX,
                            endTy = touches.clientY,
                            // distanceX = startTx - endTx,
                            distanceY = startTy - endTy;

                        if (distanceY > 50) {
                            element.className = "chat-say"
                            recordingVoice.style.display = "none"
                            recordingCancel.style.display = "block"
                        } else {
                            element.className = "chat-say say-active"
                            recordingVoice.style.display = "block"
                            recordingCancel.style.display = "none"
                        }
                        // 阻断事件冒泡 防止页面被一同向上滑动
                        e.preventDefault()
                    }, false);
                }
            },
            more: {
                bind(element) {
                    var startTx, startTy
                    element.addEventListener('touchstart', function (e) {
                        var msgMore = document.getElementById('msg-more'),
                            touches = e.touches[0];
                        startTx = touches.clientX
                        startTy = touches.clientY

                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            // 控制菜单的位置
                            msgMore.style.left = ((startTx - 18) > 180 ? 180 : (startTx - 18)) + 'px'
                            msgMore.style.top = (element.offsetTop - 33) + 'px'
                            msgMore.style.display = "block"
                            element.style.backgroundColor = '#e5e5e5'
                        }, 500)

                    }, false)
                    element.addEventListener('touchmove', function (e) {
                        var touches = e.changedTouches[0],
                            disY = touches.clientY;
                        if (Math.abs(disY - startTy) > 10) {
                            clearTimeout(this.timer)
                        }
                    }, false)
                    element.addEventListener('touchend', function () {
                        clearTimeout(this.timer)
                    }, false)
                }
            }
        },
        methods: {
          shouldShowTimestamp(index) {
            if (index === 0) return true; // 总是显示第一条消息的时间戳
            const currentMsg = this.msgInfo.msg[index];
            const previousMsg = this.msgInfo.msg[index - 1];

            const currentTime = new Date(currentMsg.date);
            const previousTime = new Date(previousMsg.date);

            // 计算时间差（以毫秒为单位）
            const hourDifference = Math.abs(currentTime - previousTime) / (1000 * 60 * 5);

            return hourDifference >= 1;
          },
          formatTimestamp(timestamp) {
            const date = new Date(timestamp); // 直接使用毫秒单位的时间戳
            const year = date.getFullYear();
            const month = date.getMonth() + 1; // JavaScript中月份是从0开始的
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          },
          parseText(text) {
            // 将文本中的图片Markdown转换为HTML，并添加点击事件监听器
            const imgRegex = /!\[.*?\]\((.*?)\)/g;
            text = text.replace(imgRegex, (match, p1) => {
              // 注意：这里的click事件需要绑定到图片上
              return `<img src="${p1}" class="resized-image" alt="Image" @click="openModal('${p1}')">`;
            });
            // 将文本中的$$股票标记转换为超链接
            const stockRegex = /\$\$(.+?)-(\d{6})/g;
            text =  text.replace(stockRegex, (match, stockName, stockCode) => {
              const linkPrefix = stockCode.startsWith('0') || stockCode.startsWith('3') ? 'SZ' : 'SH';
              const stockLink = `https://xueqiu.com/S/${linkPrefix}${stockCode}`;
              return `<a href="${stockLink}" target="_blank" style = "color: blue; font-weight: bold;">${stockName}(${stockCode})</a>`;
            });
            // 修改后的 PDF 链接转换
            const pdfRegex = /\[([^\]]+)\]\((http[^)]+\.pdf)\)/g;
            text = text.replace(pdfRegex, (match, p1, p2) => {
              return `<a href="${p2}" target="_blank" style = "color: orange; font-weight: bold;">${p1}</a>`;
            });

            // 语音消息转换逻辑
            const voiceMsgRegex = /语音消息 \[\d+秒\] \[请用手机点击收听\]\((https:\/\/static\.dingtalk\.com\/media\/.+?\.mp3)\)/g;
            text = text.replace(voiceMsgRegex, (match, p1) => {
              return `<audio controls src="${p1}">您的浏览器不支持 audio 元素。</audio>`;
            });

            return text;

          },
          openModal(imageUrl) {
            this.currentImageUrl = imageUrl;
            this.showModal = true;
          },
          closeModal() {
            this.showModal = false;
          },
          scrollToBottom() {
            this.$nextTick(() => {
              window.scrollTo(0, 99999);
            });
          },
          scrollToBottomSpan() {
              window.scrollTo(0, 99999999);
          },
            // 解决输入法被激活时 底部输入框被遮住问题
            focusIpt() {
                this.timer = setInterval(function () {
                    document.body.scrollTop = document.body.scrollHeight
                }, 100)
            },
            blurIpt() {
                clearInterval(this.timer)
            },
            // 点击空白区域，菜单被隐藏
            MenuOutsideClick(e) {
                var container = document.querySelectorAll('.text'),
                    msgMore = document.getElementById('msg-more')
                if (e.target.className !== 'text') {
                    msgMore.style.display = 'none'
                    container.forEach(item => item.style.backgroundColor = '#fff')
                }
            }
        }
    }
</script>
<style lang="less">
    @import "../../assets/less/dialogue.less";

    .say-active {
        background: #c6c7ca;
    }
</style>